import router from "@/router";
import NProgress from "@/utils/progress";
import { useTitle } from "@/hooks/useTitle";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { getToken } from "@/utils/auth";
/** 路由白名单 */
const whiteList: string[] = ["/login"];

const { setTitle } = useTitle();
router.beforeEach(async (to, _from, next) => {
  NProgress.start();
  const permissionStore = usePermissionStoreHook();

  const token = getToken("token");
  if (token) {
    // 如果已经登录，并准备进入 Login 页面，则重定向到主页
    if (to.path === "/login") {
      return next({ path: "/" });
    }
    if (
      router
        .getRoutes()
        .map((i) => i.path)
        .indexOf(to.path) !== -1
    ) {
      // 用户是否已经有菜单, 已有菜单直接放行
      next();
    } else {
      // 确保异步操作成功还是失败，next()都能调用
      try {
        await permissionStore.getMenuRouter();
        next({ ...to, replace: true });
      } catch (error) {
        next();
      }
    }
  } else {
    // 如果没有登陆
    if (to.path !== "/login") {
      // 如果在免登录的白名单中，则直接进入
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        // 其他没有访问权限的页面将被重定向到登录页面
        next({ path: "/login" });
      }
    } else {
      next();
    }
  }
});

router.afterEach((to) => {
  setTitle(to.meta?.title as string);
  NProgress.done();
});
